import subprocess
import platform

def run_command(command):
    try:
        return subprocess.check_output(command, shell=True).decode('utf-8').strip()
    except (subprocess.CalledProcessError, FileNotFoundError) as e:
        return None

def get_android_info():
    manufacturer = run_command(['adb', 'devices'])
    if manufacturer and "device" in manufacturer:
        manufacturer = run_command(['adb', 'shell', 'getprop', 'ro.product.manufacturer'])
        model = run_command(['adb', 'shell', 'getprop', 'ro.product.model'])
        if manufacturer and model:
            return {'type': 'Android', 'manufacturer': manufacturer, 'model': model}
    return None
# 获取安卓手机内安装的包名
def get_installed_packages():
    installed_packages = run_command(['adb', 'shell', 'pm', 'list', 'packages'])
    if installed_packages:
        # 过滤掉系统应用，只保留第三方应用
        packages = [line.split(':')[1].strip() for line in installed_packages.splitlines()[1:] if line]
        return packages
    return []

def get_ios_info():
    if platform.system() == 'Darwin':  # Mac系统
        model = run_command(['ideviceinfo', '--query', 'ProductType'])
    elif platform.system() == 'Windows':  # Windows系统
        model = run_command(['ideviceinfo'])
    if model:
        return {'type': 'iOS', 'model': model}
    return None

def get_harmonyos_info():
    product_name = run_command(['hdc', 'list-targets'])
    if product_name and "[Empty]" not in product_name:
        product_name = run_command(['hdc', 'shell', 'param', 'get', 'const.product.name'])
        product_brand = run_command(['hdc', 'shell', 'param', 'get', 'const.product.brand'])
        product_model = run_command(['hdc', 'shell', 'param', 'get', 'const.product.model'])
        product_software_version = run_command(['hdc', 'shell', 'param', 'get', 'const.product.software.version'])
        if all([product_name, product_brand, product_model, product_software_version]):
            return {'type': 'HarmonyOS', 'name': product_name, 'brand': product_brand, 'model': product_model, 'software_version': product_software_version}
    return None

def get_device_info():
    results = [get_android_info(), get_ios_info(), get_harmonyos_info()]
    device_info = next((info for info in results if info), "暂未识别到设备")

    if device_info and device_info.get('type') == 'Android':
        packages = get_installed_packages()
        device_info['packages'] = packages

    return device_info